<?php

namespace App\Repository\Db;

use App\Repository\Contracts\MajorInterface;

/**
 * @Author:: LuXiang
 * @DateTime: 2017/10/20 20:48
 */
class MajorRepository extends Repository implements MajorInterface
{
    protected $rules = [
        'created' => [
            'name' => 'required|min:2|max:16',
            'degree_type'=>'required|min:2|max:32',
            'major_type'=>'required|min:2|max:32'
        ],
        'updated' => [
            'name' => 'required|min:2|max:16',
            'degree_type'=>'required|min:2|max:32',
            'major_type'=>'required|min:2|max:32'
        ]
    ];

    protected $messages = [
        'name.required'         => "学校名称不能为空",
        'name.min'              => "学校名称最少两个字",
        'name.max'              => "学校名称最多16个字",
        'degree_type.required'         => "专业等级不能为空",
        'degree_type.min'              => "专业等级最少两个字",
        'degree_type.max'              => "专业等级最多32个字",
        'major_type.required'         => "专业类别不能为空",
        'major_type.min'              => "专业类别最少两个字",
        'major_type.max'              => "专业类别最多32个字",
    ];

    protected function modelName()
    {
        return 'App\Model\Major';
    }

    public function created(array $data)
    {
        $this->validate($data, 'created');

        return $this->save($data);
    }

    public function updated($id, array $data)
    {
        $this->validate($data, 'updated');

        return $this->update($data, $id, 'id');
    }

    public function detail($id, $uid)
    {
        $detail = $this->model->where('id', '=', $id)->with(['favorite' => function ($query) use ($uid) {
            $query->where('uid', '=', $uid);
        }])->with('industry')->with('job')->get();
        $data = [];
        foreach ($detail as $key => $value) {
            $data[$key] = $value->toArray();
            if ($value->industry) {
                foreach ($value->industry as $industry) {
                    $data[$key]['industry'][] = ['name' => $industry['name'], 'ratio' => $industry['ratio']];
                }
            }
            if ($value->job) {
                foreach ($value->job as $job) {
                    $data[$key]['job'][] = ['name' => $job['name'], 'ratio' => $job['ratio']];
                }
            }
            $data[$key]['is_favorite'] = $value->favorite->count() ? true : false;
        }

        return $data;
    }

    public function lists($map = [])
    {
        $query = $this->searchMap($map);
        $data = $query->get()->toArray();
        $list = [];
        foreach ($data as $key => $val) {
            $list[$val['degree_type']][$val['major_type']][$val['major_category']][] = [
                'id' => $val['id'],
                'name' => $val['name'],
            ];
        }

        return $list;
    }
}